<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryRef" :inline="true" :model="queryParams" label-width="80px">
      <el-form-item label="租客ID" prop="tenantId">
        <el-input
            v-model="queryParams.tenantId"
            clearable
            placeholder="请输入租客ID"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="租赁状态" prop="leaseStatus">
        <el-select v-model="queryParams.leaseStatus" clearable placeholder="请选择租赁状态">
          <el-option
              v-for="dict in sys_house_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始日期" style="width: 308px">
        <el-date-picker
            v-model="daterangeStartDate"
            end-placeholder="结束日期"
            range-separator="-"
            start-placeholder="开始日期"
            type="daterange"
            value-format="YYYY-MM-DD HH:mm:ss"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结束日期" style="width: 308px">
        <el-date-picker
            v-model="daterangeEndDate"
            end-placeholder="结束日期"
            range-separator="-"
            start-placeholder="开始日期"
            type="daterange"
            value-format="YYYY-MM-DD HH:mm:ss"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['system:lease:add']"
            icon="Plus"
            plain
            type="primary"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['system:lease:edit']"
            :disabled="single"
            icon="Edit"
            plain
            type="success"
            @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['system:lease:remove']"
            :disabled="multiple"
            icon="Delete"
            plain
            type="danger"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['system:lease:export']"
            icon="Download"
            plain
            type="warning"
            @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="leaseList" show-overflow-tooltip @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column align="center" label="序号" prop="count"/>
      <el-table-column align="center" label="租客" prop="tenantId"/>
      <el-table-column align="center" label="房源" prop="houseId"/>
      <el-table-column align="center" label="租赁状态" prop="leaseStatus">
        <template #default="scope">
          <dict-tag :options="sys_house_status" :value="scope.row.leaseStatus"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="房源状态" prop="delFlag">
        <template #default="scope">
          <dict-tag :options="sys_house_flag" :value="scope.row.delFlag"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="开始日期" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="结束日期" prop="endDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template #default="scope">
          <el-button v-hasPermi="['system:lease:edit']" icon="Edit" link type="primary"
                     @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button v-hasPermi="['system:lease:remove']" icon="Delete" link type="primary"
                     @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total>0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="total"
        @pagination="getList"
    />
    <!-- 添加或修改租赁关系表对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="clamp(350px,90%,600px)">
      <el-form ref="leaseRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="租客ID" prop="tenantId">
          <el-select
              v-model="form.tenantId"
              placeholder="点击选择租客"
              style="width: 240px"
          >
            <el-option
                v-for="(v,i) in users"
                :key="i"
                :label="v.nickName"
                :value="v.userId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="房源ID" prop="houseId">
          <el-select
              v-model="form.houseId"
              placeholder="点击选择房源"
              style="width: 240px"
          >
            <el-option
                v-for="(v,i) in houses.filter(v=>v.status==='1')"
                :key="i"
                :label="v.title"
                :value="v.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker v-model="form.startDate"
                          clearable
                          placeholder="请选择开始日期"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker v-model="form.endDate"
                          clearable
                          placeholder="请选择结束日期"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script name="Lease" setup>
import {addLease, delLease, getHouseList, getLease, getUserList, listLease, updateLease} from "@/api/system/lease";

const {proxy} = getCurrentInstance();
const {sys_house_status, sys_house_flag} = proxy.useDict("sys_house_status", "sys_house_flag");
const leaseList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);
const daterangeUpdateTime = ref([]);
const daterangeStartDate = ref([]);
const daterangeEndDate = ref([]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tenantId: null,
    leaseStatus: null,
    startDate: null,
    endDate: null
  },
  rules: {
    tenantId: [
      {required: true, message: "租客ID不能为空", trigger: "blur"}
    ],
    houseId: [
      {required: true, message: "房源ID不能为空", trigger: "blur"}
    ],
    startDate: [{required: true, message: "开始时间不能为空", trigger: "blur"}],
    endDate: [{required: true, message: "开始时间不能为空", trigger: "blur"}]
  }
});
const users = ref([])
const houses = ref([])
const {queryParams, form, rules} = toRefs(data);

/** 查询租赁关系表列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  if (null != daterangeUpdateTime && '' != daterangeUpdateTime) {
    queryParams.value.params["beginUpdateTime"] = daterangeUpdateTime.value[0];
    queryParams.value.params["endUpdateTime"] = daterangeUpdateTime.value[1];
  }
  if (null != daterangeStartDate && '' != daterangeStartDate) {
    queryParams.value.params["beginStartDate"] = daterangeStartDate.value[0];
    queryParams.value.params["endStartDate"] = daterangeStartDate.value[1];
  }
  if (null != daterangeEndDate && '' != daterangeEndDate) {
    queryParams.value.params["beginEndDate"] = daterangeEndDate.value[0];
    queryParams.value.params["endEndDate"] = daterangeEndDate.value[1];
  }
  getUserList().then(res => {
    users.value = res.data
  })
  getHouseList().then(res => {
    houses.value = res.data
  })
  listLease(queryParams.value).then(response => {
    leaseList.value = response.rows.map((v, i) => {
      return {
        ...v,
        count: (queryParams.value.pageNum - 1) * queryParams.value.pageSize + (i + 1),
        houseId: houses.value.find(j => j.id === v.houseId)?.title ?? '',
        tenantId: users.value.find(j => j.userId === v.tenantId)?.nickName ?? ''
      }
    });
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    tenantId: null,
    houseId: null,
    leaseStatus: '0',
    delFlag: '1',
    createTime: null,
    updateTime: null,
    startDate: null,
    endDate: null
  };
  proxy.resetForm("leaseRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  daterangeUpdateTime.value = [];
  daterangeStartDate.value = [];
  daterangeEndDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getList()
  open.value = true;
  title.value = "添加租赁关系";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getList();
  const _id = row.id || ids.value
  getLease(_id).then(response => {
    console.log(response.data)
    form.value = response.data;
    open.value = true;
    title.value = "修改租赁关系";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["leaseRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateLease(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLease(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除租赁关系表编号为"' + _ids + '"的数据项？').then(function () {
    return delLease(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/lease/export', {
    ...queryParams.value
  }, `lease_${new Date().getTime()}.xlsx`)
}

getList();
</script>
